from flask import current_app
from flask import g, jsonify
from flask import request
from info import db
from info.utlis.common import login_user_data
from info.utlis.response_code import RET
from . import profile_bp
from flask import render_template
from info.utlis.image_store import qiniu_image_store
from info import constants

@profile_bp.route('/pic_info',methods = ['GET','POST'])
@login_user_data
def pic_info():
    '''展示用户头像修改页面，修改用户头像接口'''
    if request.method =='GET':
        return render_template('news/user_pic_info.html')

    # POST获取用户上传的图片二进制数据上传到七牛云
    avatar_data = request.files.get('avatar').read()
    user = g.user

    if not avatar_data:
        return jsonify(errno=RET.NODATA, errmsg="图片数据不能为空")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    try:
        image_name = qiniu_image_store(avatar_data)
    except Exception as e:
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛云失败")

    # user.avatar_url = 域名　＋　image_name
    user.avatar_url = image_name
    try:
        db.session.commit()
    except  Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg=" 保存用户url失败")


    full_url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        'avatar_url':full_url
    }
    return jsonify(errno=RET.OK, errmsg="上传成功",data=data)


@profile_bp.route('base_info',methods = ['GET','POST'])
@login_user_data
def base_info():
    '''获取用户基本资料页面，修改用户基本资料页面'''
    user = g.user
    if request.method == 'GET':
        data = {
            'user_info':user.to_dict() if user else None
        }
    return render_template('news/user_base_info.html', data = data)
# post请求　修改用户基本资料
#     1.获取参数
    params_dict = request.json
    nick_name = params_dict.get('nick_name')
    signature = params_dict.get('signature')
    gender = params_dict.get('gender')

    if not all([nick_name,signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if action not in ('MAN','WOMAN'):
        return jsonify(errno=RET.PARAMERR, errmsg="action数据填写错误")

    # 3.逻辑处理

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    #　跟新session中的nick_name数据
    session['nick_name'] = nick_name
    #　将修改的操作保存回数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="修改用户数据异常")
    return jsonify(errno=RET.OK, errmsg="修改用户数据成功")


@profile_bp.route('/info')
@login_user_data
def user_info():
    '''返回用户个人中心页面'''
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None,
    }
    return render_template('news/user.html',data=data)
